//
//  HMWelcomeViewController.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/23.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import SDWebImage
class HMWelcomeViewController: UIViewController {

    //懒加载控件
    private lazy var backImageView:UIImageView = UIImageView(image:UIImage(named:"ad_background"))
    //自定义视图
    override func loadView() {
        view = backImageView
    }
    //头像图片
    private lazy var userImageView:UIImageView = {
        let View = UIImageView(image:UIImage(named:"avatar_default_big"))
        View.sizeToFit()
        //如果url不为空，就根据url加载用户头像
        if let url = HMUserAccountViewModel.sharedHMUserAccountViewModel.userAccount?.avatar_large {
            View.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named:"avatar_default_big"))
        }
        //切圆
        View.layer.cornerRadius = 85/2
        View.layer.masksToBounds = true
        return View
    }()
    
    //文字信息
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        if let userName = HMUserAccountViewModel.sharedHMUserAccountViewModel.userAccount?.name {
            label.text = "欢迎回来,\(userName)"
        }else{
            label.text = "欢迎回来"
        }
        
        label.alpha = 0
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpUI()
        
    }

    //设置界面
    func setUpUI() {
        view.addSubview(userImageView)
        view.addSubview(messageLabel)
        userImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(150)
        }
        
        messageLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(userImageView)
            make.top.equalTo(userImageView.snp_bottom).offset(10)
        }
    }
    
    //视图已经显示出来时执行头像动画
    override func viewDidAppear(_ animated: Bool) {
        startAnimation()
    }
    
    //让头像显示弹簧效果的动画
    private func startAnimation() {
        userImageView.snp_updateConstraints { (make) in
            make.top.equalTo(view).offset(100)
        }
        //执行约束动画
        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
            self.view.layoutIfNeeded()
            }) { (_) in
                //头像动画执行完让label恢复透明度
                UIView.animate(withDuration: 1, animations: { 
                    self.messageLabel.alpha = 1
                    }, completion: { (_) in
                        //之后切换到首页
                        //发送通知
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: nil)
                })
                
        }
    }
    
}
